package net.neptech.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.neptech.mapper.InstanceRecordMapper;
import net.neptech.model.dto.InstanceParamDto;
import net.neptech.enums.workflow.ApproveResultEnum;
import net.neptech.model.workflow.InstanceRecord;
import net.neptech.repository.InstanceRecordRepo;
import net.neptech.service.InstanceRecordService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

import static net.neptech.enums.workflow.InstanceRecordStatusEnum.*;

/**
 * @Author Saya
 * @Date 2025/8/20 11:54
 * @Description TODO
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class InstanceRecordServiceImpl extends ServiceImpl<InstanceRecordMapper, InstanceRecord> implements InstanceRecordService {
    private final InstanceRecordRepo instanceRecordRepo;

    /**
     * 根据流程实例id查询流程记录
     */
    @Override
    public InstanceRecord getByInstanceId(String instanceId) {
        return instanceRecordRepo.findById(instanceId).orElse(null);
    }

    /**
     * 清理数据
     */
    @Override
    public void clearProcess(List<String> flowIdList) {
        List<InstanceRecord> list = instanceRecordRepo.findByFlowIdIn(flowIdList);
        list.forEach(instanceRecord -> instanceRecord.setDeleted(true));
        instanceRecordRepo.saveAll(list);
    }

    @Override
    public List<InstanceRecord> getByInstanceIds(Set<String> instanceIdSet) {
        return instanceRecordRepo.findByProcessInstanceIdIn(instanceIdSet);
    }

    @Override
    public void endProcess(InstanceParamDto instanceParamDto) {
        InstanceRecord instanceRecord = instanceRecordRepo.findByProcessInstanceId(instanceParamDto.getProcessInstanceId()).stream().filter(i -> i.getStatus().equals(ON_GOING.getCode())).toList().get(0);
        if (instanceParamDto.getCancel()) {
            instanceRecord.setStatus(CANCELED.getCode());
            instanceRecord.setResult(ApproveResultEnum.CANCEL.getValue());
        } else {
            instanceRecord.setStatus(ENDED.getCode());
            instanceRecord.setResult(instanceParamDto.getResult());
        }
        instanceRecord.setEndTime(new Date());
        instanceRecordRepo.save(instanceRecord);
    }
}
